<?php

namespace App\Console\Commands;

use App\Models\Customer;
use App\Models\CustomerRecords;
use Carbon\Carbon;
use Illuminate\Console\Command;

class CustomSea extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'queue:customer_sea';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '检测过期用户进入公海';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        // 计算3个月没有成单的
        $month = 3;
        $end = Carbon::now()->subMonths($month)->endOfMonth();
        $customers = Customer::where('created_at', '<', $end)->where('is_order', false)->get();

        // 自动进入公海
        Customer::whereIn('id', $customers->modelKeys())->update(['is_sea' => true]);

        // 计算连续多少天没跟进的
        $days = 15;

        $end = Carbon::now()->subDays($days)->endOfDay();
        $sub = CustomerRecords::groupBy('customer_id')->selectRaw('id, max(created_at) as max_created_at');
        $sql = DB::table($sub, 'b')->selectRaw('customer_id')->where('max_created_at', '>', $sub);
        Customer::whereNotIn('id', $sql)->where('is_order', false)->update(['is_sea' => true]);

        $this->info("自动计算客户进入公海成功");
        return 0;
    }
}
